import constant
import lcs

China = constant.China
OutPut = constant.OutPut
Expert = OutPut + "_Expert"
ExpertTmp = Expert + "_Tmp"
ExpertTmp1 = ExpertTmp + "1"


def escapeCharacter(str):
    """
    数据库sql字符串转义
    \n ' 转义为  ''
    \n { 转义为  {{
    \n } 转义为  }}
    :param str:
    :return:
    """

    return str.replace("'", "''").replace("{", "{{").replace("}", "}}")


def getDbStr(strParam):
    strParam = str(strParam)
    max = len(strParam)
    i = 0
    while True:
        strParam = strParam.strip()
        if strParam.startswith("'"):
            strParam = strParam[1:]
        if strParam.endswith("'"):
            strParam = strParam[:len(strParam) - 1]
        if strParam.endswith("\\"):
            strParam = strParam[:len(strParam) - 1]
        if not strParam.startswith("'") and not strParam.endswith("'") and not strParam.endswith("\\"):
            # 收尾的单引号都删除后，返回
            break
        i += 1
        if i > max:
            # 防止死循环
            break
    return "'" + strParam + "'"


def isSameExpert(client, x, y, Expert):
    """
    相同 org，合并 name ；
    传入两个 Expert 的 uuid，验证，这两个专家是不是同一个人。
    判断依据：1.是否有相同研究领域。2.是否在同一刊物发表过期刊。3.是否有相同关键词
    三个条件满足一个，就算同一个人
    """

    xJournalsMap = {}
    xKeywordsMap = {}
    xSubjectsMap = {}
    xSecondOrgMap = {}
    sep = ";"
    xsql = (
            " select ifnull(journals,'') ,ifnull(keywords,'') ,ifnull(subjects,'') ,ifnull(Second_organization,'') from " + Expert +
            " where uuid = " + getDbStr(escapeCharacter(x)) + " limit 1 "
    )
    xrows = client.execute(xsql)
    if xrows is not None and len(xrows) > 0:
        xJournals = xrows[0][0]
        if xJournals is not None and xJournals != "":
            xJournalsArr = xJournals.split(sep)
            for item in xJournalsArr:
                xJournalsMap[item] = 1
        xkeywords = xrows[0][1]
        if xkeywords is not None and xkeywords != "":
            xkeywordsArr = xkeywords.split(sep)
            for item in xkeywordsArr:
                xKeywordsMap[item] = 1
        xsubjects = xrows[0][2]
        if xsubjects is not None and xsubjects != "":
            xsubjectsArr = xsubjects.split(sep)
            for item in xsubjectsArr:
                xSubjectsMap[item] = 1
        xSecondOrg = xrows[0][3]
        if xSecondOrg is not None and xSecondOrg != "":
            xSecondOrgArr = xSecondOrg.split(sep)
            for item in xSecondOrgArr:
                xSecondOrgMap[item] = 1
    ysql = (
            " select ifnull(journals,'') ,ifnull(keywords,'') ,ifnull(subjects,'') ,ifnull(Second_organization,'') from " + Expert +
            " where uuid = " + getDbStr(escapeCharacter(y)) + " limit 1 "
    )
    yrows = client.execute(ysql)
    if yrows is not None and len(yrows) > 0:
        yJournals = yrows[0][0]
        if yJournals is not None and yJournals != "":
            yJournalsArr = yJournals.split(sep)
            for item in yJournalsArr:
                if item in xJournalsMap.keys():
                    return True
        ykeywords = yrows[0][1]
        if ykeywords is not None and ykeywords != "":
            ykeywordsArr = ykeywords.split(sep)
            for item in ykeywordsArr:
                if item in xKeywordsMap.keys():
                    return True
        ysubjects = yrows[0][2]
        if ysubjects is not None and ysubjects != "":
            ysubjectsArr = ysubjects.split(sep)
            for item in ysubjectsArr:
                if item in xSubjectsMap.keys():
                    return True
        ySecondOrg = yrows[0][3]
        if ySecondOrg is not None and ySecondOrg != "":
            ySecondOrgArr = ySecondOrg.split(sep)
            for item in ySecondOrgArr:
                if item in xSecondOrgMap.keys():
                    return True

    return False


def isSameExpert_org(client, x, y):
    """
    相同 org，合并 name ；
    传入两个 Expert 的 uuid，验证，这两个专家是不是同一个人。
    判断依据：1.是否有相同研究领域。2.是否在同一刊物发表过期刊。3.是否有相同关键词
    """

    return isSameExpert(client, x, y, ExpertTmp)


def isSameExpert_name(client, x, y):
    """
    相同 name ，合并 org ；
    传入两个 Expert 的 uuid，验证，这两个专家是不是同一个人。
    判断依据：1.是否有相同研究领域。2.是否在同一刊物发表过期刊。3.是否有相同关键词
    """

    return isSameExpert(client, x, y, ExpertTmp1)


def isSameExpert_2(xKeywords, xSubjects, xJournals, xSecondOrg,
                   yKeywords, ySubjects, yJournals, ySecondOrg):
    """
    step2_1~7 相同 name ，合并 org ；
    传入两个 Expert ，验证，这两个专家是不是同一个人。
    判断依据：1.是否有相同研究领域。2.是否在同一刊物发表过期刊。3.是否有相同关键词，4.二级机构是否有交集
    """

    seq = ";"

    xKeywordsArr = []
    if xKeywords != None and xKeywords != "":
        xKeywordsArr = xKeywords.split(seq)
    xSubjectsArr = []
    if xSubjects != None and xSubjects != "":
        xSubjectsArr = xSubjects.split(seq)
    xJournalsArr = []
    if xJournals != None and xJournals != "":
        xJournalsArr = xJournals.split(seq)
    xSecondOrgArr = []
    if xSecondOrg != None and xSecondOrg != "":
        xSecondOrgArr = xSecondOrg.split(seq)

    yKeywordsArr = []
    if yKeywords != None and yKeywords != "":
        yKeywordsArr = yKeywords.split(seq)
    ySubjectsArr = []
    if ySubjects != None and ySubjects != "":
        ySubjectsArr = ySubjects.split(seq)
    yJournalsArr = []
    if yJournals != None and yJournals != "":
        yJournalsArr = yJournals.split(seq)
    ySecondOrgArr = []
    if ySecondOrg != None and ySecondOrg != "":
        ySecondOrgArr = ySecondOrg.split(seq)

    if len(xKeywordsArr) > 0 and len(yKeywordsArr) > 0:
        for v in xKeywordsArr:
            if v in yKeywordsArr:
                return True
    if len(xSubjectsArr) > 0 and len(ySubjectsArr) > 0:
        for v in xSubjectsArr:
            if v in ySubjectsArr:
                return True
    if len(xJournalsArr) > 0 and len(yJournalsArr) > 0:
        for v in xJournalsArr:
            if v in yJournalsArr:
                return True
    if len(xSecondOrgArr) > 0 and len(ySecondOrgArr) > 0:
        for v in xSecondOrgArr:
            if v in ySecondOrgArr:
                return True
    return False


def isCommonPart(x, y):
    """
    若存在交集，则为同一个专家
    """
    if x == "" or y == "":
        return False
    xArr = x.split(";")
    yArr = y.split(";")

    if len(xArr) > len(yArr):
        arr = xArr
        dict = yArr
    else:
        arr = yArr
        dict = xArr

    for item in arr:
        if item in dict:
            return True

    return False


def isCommonPartByEmail(e1, e2):
    if e1 is None or e2 is None:
        return False, ""
    e1Arr = e1.strip().split(";")
    e2Arr = e2.strip().split(";")

    if len(e1Arr) > len(e2Arr):
        arr = e2Arr
        dictArr = e1Arr
    else:
        arr = e1Arr
        dictArr = e2Arr
    for e in arr:
        if e in dictArr:
            return True, e
    return False, ""


def checkAndGetSingleEmail(xEmail, yEmail, name, organization):
    """
    x为主
    """

    emailnew = ""
    emailCount = 0

    emailMap = {}
    emailArr = []

    if xEmail is None or yEmail is None:
        return emailnew
    xEmailArr = getNotNullArr(xEmail.split(";"))
    for i in xEmailArr:
        if i not in emailArr:
            emailArr.append(i)
        if i not in emailMap.keys():
            emailMap[i] = 1
        else:
            emailMap[i] += 1
    yEmailArr = getNotNullArr(yEmail.split(";"))
    # 取交集，出现最多的
    for i in yEmailArr:
        if i not in emailArr:
            emailArr.append(i)
        if i not in emailMap.keys():
            emailMap[i] = 1
        else:
            emailMap[i] += 1
    if len(xEmailArr) == 0 and len(yEmailArr) == 0:
        return emailnew
    for k in emailMap.keys():
        if emailMap[k] == 1:
            continue
        if emailMap[k] > emailCount:
            emailCount = emailMap[k]
            emailnew = k
    if emailCount != 0:
        return emailnew
    # 都没有交集，根据名字，机构，判断邮箱归属
    for itemEmail in emailArr:
        emailHead = "" if itemEmail is None else itemEmail[0:itemEmail.find('@')]
        emailOrg = "" if itemEmail is None else itemEmail[itemEmail.find('@') + 1:itemEmail.find('.')]
        if lcs.isLCS(name, emailHead) and lcs.isLCS(organization, emailOrg):
            if emailnew == "":
                emailnew = itemEmail
            tmpEmail = itemEmail
            if len(emailnew) > len(tmpEmail):
                emailnew = tmpEmail
    if emailnew != "":
        return emailnew
    if len(xEmailArr) != 0:
        emailnew = xEmailArr[0]
        return emailnew
    if len(yEmailArr) != 0:
        emailnew = yEmailArr[0]
    return emailnew


def getNotNullArr(arr):
    res = []
    if arr is None or len(arr) == 0:
        return res
    for i in arr:
        if i.strip() != '':
            res.append(i.strip())
    return res


if __name__ == '__main__':
    # uuidI = '9e7e3b04-fbdb-40e4-afbb-e7568135a69b'
    # uuidJ = '4bd413ae-271f-48c3-9900-bcecf13e7468'
    # uuidI = 'b8c75dec-f88f-4ac4-9e83-015de159b5bb'
    # uuidJ = '42a121b0-3e6c-4a5b-b80f-f313f03e4550'
    # sameExpert = isSameExpert_name(uuidI, uuidJ)
    # print(sameExpert)
    print("")
